#!/bin/bash

hostname_id=`echo $MY_POD_NAME | awk -F- '{print $NF}'`

echo $hostname_id
dns_name=${MY_POD_NAME}.${MY_POD_SERVICE}.default.svc.cluster.local
# check dns status
a=1
while [ $a -ne "0" ]
do
    echo "next"
    ping -c 2 ${dns_name}
    a=$?
    sleep 1
done

check_nn1(){
    echo "check nn1 "
    nc -zvw3 namenode-0.hadoop.default.svc.cluster.local 8020
    if [ $? -ne 0 ];
    then
       echo "nn1 namenode check fail"
       exit 1
    fi

}

init_namenode(){
    echo "namenode init"
    if [ ! -e "/data1/name/current/VERSION" ];
    then
      if [ $hostname_id -eq "0"  ]; 
      then
         hdfs namenode -format >> /data1/logs/init.log 2>&1 
         echo Y | hdfs zkfc -formatZK >> /data1/logs/init.log 2>&1
      fi 
      if [ $hostname_id -eq "1"  ]; 
      then
         check_nn1
         hdfs namenode -bootstrapStandby >> /data1/logs/init.log 2>&1
      fi 
    fi 
}

check_journalnode(){
    echo "check fail"
    nc -zvw3 journalnode-2.hadoop.default.svc.cluster.local 8485
    if [ $? -ne 0 ];
    then
       echo "journal node check fail"
       exit 1
    fi
}

echo $HADOOP_CONF_DIR
ls -la /etc/hadoop-conf

case "$1" in
  namenode)
    check_journalnode
    init_namenode 
    hadoop-daemon.sh --script hdfs stop namenode
    hadoop-daemon.sh --script hdfs start namenode
    hadoop-daemon.sh --script hdfs stop zkfc
    hadoop-daemon.sh --script hdfs start zkfc
    sh /opt/daemon.sh NameNode
  ;;
  datanode)
    hadoop-daemon.sh --script hdfs start datanode
    #sh /opt/daemon.sh DataNode
  ;;
  journalnode)
    hadoop-daemon.sh start journalnode
    sh /opt/daemon.sh JournalNode
  ;;
  bash)
    /bin/bash
  ;;
esac

#exec /usr/bin/tini -s -- "${CMD}"
